from xml.sax.saxutils import XMLGenerator
import datetime, time
from docutils.core import publish_parts
import email

def rfc2822_date(date):
    return email.Utils.formatdate(time.mktime(date.timetuple()))

class SimpleXMLGenerator(XMLGenerator):
    def addQuickElement(self, name, contents=None, attrs=None):
        "Convenience method for adding an element with no children"
        if attrs is None: attrs = {}
        self.startElement(name, attrs)
        if contents is not None:
            self.characters(contents)
        self.endElement(name)   

class Rss2Feed(object):
    def __init__(self,*args,**kwargs):
        """Writes the RSS File."""
        # Write the metadata for the RSS File first.
        self.keyword_args = kwargs.copy()
        handler = SimpleXMLGenerator()
        handler.startDocument()
        handler.startElement(u"rss", {u"version": u"2.0",u"xmlns:atom":u"http://www.w3.org/2005/Atom"})
        handler.startElement(u"channel", {})
        handler.startElement(u"""atom:link href="http://ilughyd.org.in/lug_meeting.xml" rel="self" type="application/rss+xml"/""",{})
        handler.addQuickElement(u"title", self.keyword_args.get('title'))
        handler.addQuickElement(u"link", self.keyword_args.get('link'))
        handler.addQuickElement(u"description", self.keyword_args.get('description'))
        if self.keyword_args.get('language') is not None:
            handler.addQuickElement(u"language", self.keyword_args.get('language'))
        handler.addQuickElement(u"category", self.keyword_args.get('categories'))
        if self.keyword_args.get('feed_copyright') is not None:
            handler.addQuickElement(u"copyright", self.keyword_args.get('feed_copyright'))
        handler.addQuickElement(u"lastBuildDate", rfc2822_date(datetime.datetime.now()).decode('ascii'))
        if self.keyword_args.get('ttl') is not None:
            handler.addQuickElement(u"ttl", self.keyword_args.get('ttl'))
        self.write_items(handler)
        handler.endElement(u"channel")
        handler.endElement(u"rss")

    def write_items(self,handler):
        """
        Write the items into the RSS File.
        """
        # Write Items
        handler.startElement(u"item", {})
        handler.addQuickElement(u"title", self.keyword_args.get('item').get('title'))
        handler.addQuickElement(u"link", self.keyword_args.get('item').get('link'))
        if self.keyword_args.get('item').get('description') is not None:
            handler.addQuickElement(u"description", self.keyword_args.get('item').get('description'))
        # Author information.
        if self.keyword_args.get('item').get("author_name") and self.keyword_args.get('item').get("author_email"):
            handler.addQuickElement(u"author", "%s (%s)" % \
                                    (self.keyword_args.get('item').get('author_email'), 
                                     self.keyword_args.get('item').get('author_name')))
        elif self.keyword_args.get('item').get("author_email"):
            handler.addQuickElement(u"author", self.keyword_args.get('item').get("author_email"))
        elif self.keyword_args.get('item').get("author_name"):
            handler.addQuickElement(u"dc:creator", self.keyword_args.get('item').get("author_name"), {"xmlns:dc": u"http://purl.org/dc/elements/1.1/"})
        if self.keyword_args.get('item').get('pubdate') is not None:
            handler.addQuickElement(u"pubDate", rfc2822_date(self.keyword_args.get('item').get('pubdate')).decode('ascii'))
        if self.keyword_args.get('item').get('unique_id') is not None:
            handler.addQuickElement(u"guid", self.keyword_args.get('item').get('unique_id'))
        if self.keyword_args.get('item').get('ttl') is not None:
            handler.addQuickElement(u"ttl", self.keyword_args.get('item').get('ttl'))
        # Categories.
        for cat in self.keyword_args.get('item').get('categories'):
            handler.addQuickElement(u"category", cat)
        handler.endElement(u"item")                      


def main():
    from meet_day_script import calc_meet_date

    venue = "Department of Astronomy,Osmania University"

    meet_time = "2:00 PM"

    y,m,d = calc_meet_date(int(time.strftime('%Y')),int(time.strftime('%m')))
    
    if datetime.date.today() > datetime.date(y,m,d):
        y,m,d = calc_meet_date(None,m+1)

    try:
        agenda_file = open("/home/ilughyd/agendas/agenda_%d%d%d.txt" %(y,m,d),"r")
        agenda_text = agenda_file.read().strip()
    except IOError:
        agenda_text = "Agenda not yet set."
    agenda_content = """%s""" %(agenda_text)
    final_agenda_content = publish_parts(source=agenda_content, writer_name="html4css1")['html_body']+\
					 '\n The meeting is on %s at %s at %s' \
			   %(datetime.datetime.strptime('%s-%s-%s' %(y,m,d),"%Y-%m-%d").strftime("%d %B, %Y (%A)"), \
			     venue, meet_time)
    item_dict = {
              "title":u"Lug Monthly Meet Feeds",
              "link":u"http://ilughyd.org.in/",
              "description":final_agenda_content,
              "author_email":u"webmaster@ilughyd.org.in",
              "author_name":u"Webmaster",
              "author_link":u"http://ilughyd.org.in/",
              "categories":[u"LUG Meet Agenda",],
              "unique_id":u"http://ilughyd.org.in/lug_meeting.xml",        
            }

    feed = Rss2Feed(
        title=u"ILugHyd Monthly Meet Feeds",
        link=u"http://ilughyd.org.in/",
        description=u"Meeting Agenda from Ilughyd.org.in",
        language=u"en-us",
        author_email=u"webmaster@ilughyd.org.in",
        author_name=u"Webmaster",
        author_link=u"http://ilughyd.org.in/",
        feed_url=u"http://ilughyd.org.in/lug_meeting.xml",
        feed_copyright=u"Creative Commons Share-Alike Attribution India License v 2.5",
        categories=u"LUG Meets",
        item=item_dict,
        )

if __name__ == '__main__':
    main()

